import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import publicRoutes from './public-routes';

const routes = [
  {
    path: '/',
    component: () => import('@/layouts/index.vue'),
    children: [
      {
        path: '',
        component: () => import('@/views/dashboard/Example.vue'),
      },
      {
        path: 'mail',
        component: () => import('@/views/mail/Example.vue'),
      },
      {
        path: 'video',
        component: () => import('@/views/music/Example.vue'),
      },
      {
        path: 'tasks',
        component: () => import('@/views/tasks/Example.vue'),
      },
    ],
  },

  // 系统管理
  {
    path: '/system',
    component: () => import('@/layouts/index.vue'),
    children: [
      {
        path: 'user-management',
        component: () => import('@/views/system/user/index.vue'),
      },
      {
        path: 'department-management',
        component: () => import('@/views/system/department/index.vue'),
      },
      {
        path: 'dictionary-management',
        component: () => import('@/views/system/dictionary/index.vue'),
      },
    ],
  },

  {
    path: '/common',
    component: () => import('@/layouts/index.vue'),
    children: [
      {
        path: 'account-setting',
        component: () => import('@/views/common/account-setting/index.vue'),
      },
      {
        path: 'notifications',
        component: () => import('@/views/common/notifications/index.vue'),
      },
      {
        path: 'ask',
        component: () => import('@/views/ask/index.vue'),
      },
    ],
  },

  ...publicRoutes,
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, _from, next) => {
  const authStore = useAuthStore();

  // 检查路由是否需要认证（默认需要认证）
  const requiresAuth = to.meta.requiresAuth !== false;

  // 如果是公共路由（不需要认证）
  if (!requiresAuth) {
    // 如果已登录且访问登录页，重定向到首页
    if (to.path === '/login' && authStore.isLoggedIn) {
      next('/');
      return;
    }
    // 其他公共路由直接放行
    next();
    return;
  }

  // 需要认证的路由
  if (!authStore.isLoggedIn) {
    // 未登录，重定向到登录页，并保存原始目标路径
    next({
      path: '/login',
      query: { redirect: to.fullPath },
    });
  } else {
    // 已登录，允许访问
    next();
  }
});

export default router;
